package com.heima.user.service.impl;

import com.heima.common.constants.message.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {


    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 用户关注/取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1 参数校验
        if (dto.getAuthorApUserId()==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者对应的userId不存在");
        }
        //2 判断用户是否登陆
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户需要先进行登陆才可以进行操作");
        }
        //3 判断操作状态是否正常
        int operation = dto.getOperation().intValue();
        if (operation!=0&&operation!=1) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"关注类型错误");
        }
        //4 当用户操作状态事0的时候 执行关注操作
        Integer loginId = user.getId();
        Integer followId = dto.getAuthorApUserId();
        // 查询该用户是否已经关注该作者
        Double score = redisTemplate.opsForZSet()
                .score(UserRelationConstants.FOLLOW_LIST + loginId, String.valueOf(followId));

        if (operation==0) {
            //4.1 判断用户是否自己关注自己
            if (followId.equals(loginId)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户不可以自己关注自己！！");
            }
            //4.2 判断用户是否已经关注过该作者
            if(score!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"您已关注，请勿重复关注");
            }
            //4.3 如果没有则执行关注，首先在关注列表中执行添加作者，然后在粉丝列表中添加粉丝
            redisTemplate.opsForZSet().
                    add(UserRelationConstants.FOLLOW_LIST + loginId,String.valueOf(followId),System.currentTimeMillis());
            redisTemplate.opsForZSet().
                    add(UserRelationConstants.FANS_LIST + followId,String.valueOf(loginId),System.currentTimeMillis());
        }else {
            //5 当用户的操作状态事1的时候  执行取消关注操作
            if(score==null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"您已取消关注了哦");
            }
            redisTemplate.opsForZSet().
                    remove(UserRelationConstants.FOLLOW_LIST + loginId,String.valueOf(followId));
            redisTemplate.opsForZSet().
                    remove(UserRelationConstants.FANS_LIST + followId,String.valueOf(loginId));

        }
        return ResponseResult.okResult();
    }
}
